import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Toast } from 'vant'
import { Base64 } from 'js-base64'
import constant from '@/common/constant/httpStatus'
import { axiosBeseUrl } from '@/common/config/baseConfig'

function isIosOrAndroid () {
  var u = navigator.userAgent
  var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
  if (isAndroid) {
    return 'android'
  }
  var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  if (isiOS) {
    return 'ios'
  }
}
async function getInfo () {
  const isAndroid = isIosOrAndroid()
  if (isAndroid == 'android') {
    this.token = await window.paiApp.getToken()
    // this.baseUrl = await window.paiApp.getApiBaseUrl()
    this.isBack = 2
  } else if (isAndroid == 'ios') {
    window.connectWebViewJavascriptBridge(bridge => {
      bridge.registerHandler('getToken', (data) => {
        this.token = data.token
        this.baseUrl = data.baseUrl
        this.isBack = 3
      })
    })
  }
}
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
const instance = axios.create({
  timeout: 10000
})
instance.defaults.baseURL = axiosBeseUrl

// request拦截器
instance.interceptors.request.use(config => {
  const clientId = process.env.VUE_APP_CLIENT_ID
  const clientSecret = process.env.VUE_APP_CLIENT_SECRET
  config.headers.Authorization = `Basic ${Base64.encode(`${clientId}:${clientSecret}`)}`
  config.headers.token = 'Bearer '
  config.headers.tenant = 'MDAwMQ=='
  // Do something before request is sent
  // if (store.getters.token) {
  config.headers.token = 'Bearer eyJ0eXAiOiJKc29uV2ViVG9rZW4iLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoidG9rZW4iLCJ1c2VyaWQiOiIxNDczMTgxMzQyMTEwODQyODgwIiwiYWNjb3VudCI6IjE3NjEyMTY1MzEzIiwiaWF0IjoxNjQ1NTgyNjQ2LCJuYmYiOjE2NDU1ODI2NDYsImV4cCI6MTY0NjAxNDY0Nn0.PBSETYIGprlS_GI_DHwfVSN4VVnw6wizjbxVLkSTPg0' || store.getters.token // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
  // }
  if (!store.getters.token) {
    // getInfo()
  }
  console.log(config)
  return config
}, error => {
  Promise.reject(error)
})
// respone 拦截器
instance.interceptors.response.use(res => {
  if (res.status === 200) {
    const data = res.data
    console.log(data.code)
    if (constant.NO_LOGIN === data.code) {
      console.log(res)
      Toast.fail(data.msg)
      removeToken()
      store.commit('user/SIGN_OUT')
      setTimeout(() => {
        router.push({ path: '/login' })
      }, 500)
    } else if (constant.SUCCESS === data.code) {
      return data.data
    } else {
      Toast.fail(data.msg)
      return data
    }
    // returnCode(data)
  }
}, error => {
  console.log(error)
  return Promise.reject(error)
}
)

export default instance
